package io.feige.rpc.spring;

import io.feige.rpc.consumer.RpcConsumerService;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ReferenceBean implements FactoryBean<Object>, ApplicationContextAware, InitializingBean, DisposableBean {
 
	private static RpcConsumerService rpcConsumerService;
	
	private String interfaceName; 

	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if (rpcConsumerService==null) {
			rpcConsumerService=new RpcConsumerService();
			rpcConsumerService.start();
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException { 

	}

	@Override
	public Object getObject() throws Exception {
		return rpcConsumerService.getProxyService(Class.forName(interfaceName));
	}

	@Override
	public Class<?> getObjectType() { 
		try {
			return Class.forName(this.interfaceName);
		} catch (Exception e) {
			return null;
		}
	}

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }
    
    public void setInterface(Class<?> interfaceClass) {
        if (interfaceClass != null && ! interfaceClass.isInterface()) {
            throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
        } 
        setInterfaceName(interfaceClass == null ? (String) null : interfaceClass.getName());
    }
	
	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void destroy() throws Exception {
		rpcConsumerService.destroy();
	}

}